package tetris;

/**
 * Created by IntelliJ IDEA.
 * User: raycom
 * Date: 20.09.10
 * Time: 16:45
 */
public class CharBoard implements Board<String, CharBlock> {
    private static final char BLANK_SYMBOL = '*';


    private int columns, rows;
    final char[][] charArray;
    private CharBlock fallingBlock;
    private CharBlock previousBlock;
    private int filledRows = 0;

    public CharBoard(int columns, int rows) {
        this.columns = columns;
        this.rows = rows;

        charArray = new char[columns][rows];

        for (int i = 0; i < rows; i++)
            for (int j = 0; j < columns; j++)
                charArray[i][j] = BLANK_SYMBOL;

    }

    public String render() {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < columns; j++) {
                sb.append(charArray[i][j]);
            }
            sb.append("\n");
        }

        return sb.toString();
    }

    public Boolean isFallingBlocks() {
        return fallingBlock != null;
    }

    public void drop(CharBlock block) {
        fallingBlock = previousBlock = block;
        int col = getTheMiddleColumn();
        charArray[0][col] = block.getCh();
        if (((charArray.length > 1) && (charArray[1][col] != BLANK_SYMBOL)) || charArray.length == 1) {
            filledRows++;
            fallingBlock = null;
        }
    }

    private int getTheMiddleColumn() {
        if (columns % 2 == 0) {
            return columns / 2 - 1;
        } else {
            return columns / 2;
        }
    }

    public void tick() {
        if (fallingBlock == null) {
            drop(new CharBlock(previousBlock.getCh()));
        } else {
            int col = getTheMiddleColumn();
            int freeRows = rows - filledRows;
            for (int row = 0; row < freeRows; row++) {
                char curChar = charArray[row][col];
                if (curChar != BLANK_SYMBOL) {
                    if ((freeRows - row) == 2) {
                        filledRows++;
                        fallingBlock = null;
                    }
                    charArray[row + 1][col] = curChar;
                    charArray[row][col] = BLANK_SYMBOL;
                    break;
                }
            }
        }
    }

    public Boolean isGameOver() {
        for (int i = 0; i < rows; i++) {
            if (charArray[i][getTheMiddleColumn()] == BLANK_SYMBOL) {
                return false;
            }
        }
        return true;
    }
}
